<template>
  <div>
      <van-cell v-for="(item,index) in list" :key="index" icon="search" @click="$emit('search-event',item)">
        <template #title>
          <span v-html="highlight(item)"></span>
        </template>
      </van-cell>
  </div>
</template>
<script>
import { getSearchSuggestions } from '@/api/search'
// 第一步 npm i lodash 安装一下
import { debounce } from 'lodash'
export default {
  name: 'SearchSuggestion',
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  watch: {
    searchText: {
      handler: debounce(function (value) {
        this.getList(value)
      }, 1000),
      immediate: true// 第一次也会监听
    }
  },
  data () {
    return {
      list: [],
      // 把数据格式从一种格式转换成另一种格式，过滤器
      str: '111'
    }
  },
  methods: {
    async getList (q) {
      try {
        const { data: res } = await getSearchSuggestions(q)
        this.list = res.data.options
      } catch (err) {
        this.$toast.fail('获取建议数据失败')
      }
    },
    highlight (str) {
      var reg = new RegExp(this.searchText, 'gi')
      return str.replace(reg, '<span style="color:red">' + this.searchText + '</span>')
    }
  }
}
</script>
<style scoped lang="less">

</style>
